package com.springboot.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.base.common.BusinessException;
import com.springboot.base.common.EmBusinessError;
import com.springboot.base.dal.UserMapper;
import com.springboot.base.model.User;
import com.springboot.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-07-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User qryById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    @Transactional
    public User register(User registerUser) throws UnsupportedEncodingException, NoSuchAlgorithmException, BusinessException {
        registerUser.setPassword(encodeByMd5(registerUser.getPassword()));
        registerUser.setCreatedAt(new Date());
        registerUser.setUpdatedAt(new Date());
        try {
            userMapper.insert(registerUser);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(EmBusinessError.REGISTER_DUP_FAIL);
        }
        System.out.println(registerUser.getId());
        return registerUser;
    }

    @Override
    public User login(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        user.setPassword(encodeByMd5(user.getPassword()));
        return userMapper.login(user);
    }

    @Override
    public Integer countAllUser() {
        return userMapper.selectCount(Wrappers.query());
    }

    private String encodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确认计算方法MD5
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(messageDigest.digest(str.getBytes("utf-8")));

    }
}
